package com.tian.exception;

import com.tian.util.CommonResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindException;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.servlet.http.HttpServletRequest;
import javax.validation.ConstraintViolationException;

/**
 * @author tianwc  公众号：java后端技术全栈、面试专栏
 * @version 1.0.0
 * @date 2023年5月27日 20:48
 * <p>
 * 全局异常处理
 */

@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {

    /**
     * 请求方式不支持
     */
    @ExceptionHandler(HttpRequestMethodNotSupportedException.class)
    public CommonResult<String> handleHttpRequestMethodNotSupported(HttpRequestMethodNotSupportedException e, HttpServletRequest request) {
        log.warn("请求方式不支持 {} {}", request.getServletPath(), e.getMethod());
        return CommonResult.failed(e.getMessage());
    }

    /**
     * 参数验证错误
     */
    @ExceptionHandler(BindException.class)
    public CommonResult<String> handleBindException(BindException e, HttpServletRequest request) {
        String message = e.getAllErrors().get(0).getDefaultMessage();
        log.warn("请求参数错误 {} {}", request.getServletPath(), message);
        return CommonResult.failed(message);
    }

    /**
     * 参数绑定异常
     */
    @ExceptionHandler(MissingServletRequestParameterException.class)
    public CommonResult<String> handleBindException(MissingServletRequestParameterException e, HttpServletRequest request) {
        String message = e.getMessage();
        log.warn("参数绑定异常 {} {}", request.getServletPath(), message);
        return CommonResult.failed(e.getParameterName() + " 未提供");
    }

    /**
     * 参数验证错误
     */
    @ExceptionHandler(ConstraintViolationException.class)
    public CommonResult<String> handleBindException(ConstraintViolationException e, HttpServletRequest request) {
        String message = e.getMessage();
        log.warn("参数验证错误 {} {}", request.getServletPath(), message);
        return CommonResult.failed(e.getMessage());
    }
}